import traceback
from django.http import JsonResponse
from django.views import View
from ...serializers.unitSetSerializer import *
from ...config.basic_config import type_conversion_dict
from ...utils.common_util.basic_util import get_model_serializer_config
from ...utils.related_util.choice_util import get_unit_set_choices, get_quantity_type_choices, get_valid_show_unit_choices_by_quantity
from ...config.message_config import Config_message_type, Config_message, Error_message_type
from utils.responseContentUtil import *

class UnitSetConfigView(View):
    def get(self, request):
        res = {"code": 400, "message": "", "data": None}
        try:
            data = {}
            query_fields = UnitSetListQuerySerializer.get_query_fields()
            for query_field in query_fields:
                query_field["type"] = type_conversion_dict[query_field["type"]]
            data["query_fields"] = query_fields
            table_fields = get_model_serializer_config(UnitSetListSerializer)
            table_extra_fields = UnitSetListSerializer.get_extra_fields_info()
            for extra_field in table_extra_fields:
                for field in table_fields:
                    if field["dataIndex"] == extra_field["dataIndex"]:
                        field["type"] = extra_field["type"]
                        field["title"] = extra_field["title"]
                        break
            table_fields.append(
                {"dataIndex": "operate", "title": "操作", "type": "operate"})
            hidden_fields = ["uuid"]
            sortable_fields = []
            link_fields = ["unit_set_name"]
            for field in table_fields:
                field["type"] = type_conversion_dict[field["type"]]
                if field["dataIndex"] in hidden_fields:
                    field["hidden"] = True
                if field["dataIndex"] in sortable_fields:
                    field["sortable"] = True
                if field["dataIndex"] in link_fields:
                    field["isLink"] = True
            data["table_fields"] = table_fields
            return make_get_success_response(data=data)
        except Exception as e:
            traceback.print_exc()
            return make_server_error_response(message=str(e), data=None)


class UnitSetCreateConfigView(View):
    def get(self, request):
        res = {"code": 400, "message": "", "data": None}
        try:
            data = {}
            create_fields = get_model_serializer_config(
                UnitSetCreateSerializer)
            create_extra_fields = UnitSetCreateSerializer.get_extra_fields_info()
            for extra_field in create_extra_fields:
                for field in create_fields:
                    if field["dataIndex"] == extra_field["dataIndex"]:
                        field["type"] = extra_field["type"]
                        field["title"] = extra_field["title"]
                        break
            single_choice_fields = ["origin_unit_set"]
            single_choice_field_dict = {}
            single_choice_field_dict["origin_unit_set"] = get_unit_set_choices(
            )
            json_fields = ["unitsetcontent"]
            json_fields_type = {"unitsetcontent": "tab"}
            json_fields_dict = {}
            unitsetcontent_content = []
            quantity_type_list = get_quantity_type_choices()
            availabel_quantitys = UnitSetContent.objects.all().values_list("quantity__uuid").distinct()
            for quantity_type in quantity_type_list:
                quantitys = Quantity.objects.filter(uuid__in=availabel_quantitys,
                    quantity_type=quantity_type["value"], valid_flag=True)
                if quantitys.count() == 0:
                    continue
                quantity_contents = []
                for quantity in quantitys:
                    quantity_contents.append({
                        "title": quantity.show_short_name(),
                        "dataIndex": quantity.uuid,
                        "type": "short_string",
                        "singleChoice": True,
                        "required": True,
                        "choices": get_valid_show_unit_choices_by_quantity(quantity)
                    })
                unitsetcontent_content.append({
                    "title": quantity_type["label"],
                    "dataIndex": quantity_type["value"],
                    "type": "json",
                    "content": quantity_contents
                })
            json_fields_dict["unitsetcontent"] = unitsetcontent_content
            for create_field in create_fields:
                create_field["type"] = type_conversion_dict[create_field["type"]]
                if create_field["dataIndex"] in single_choice_fields:
                    create_field["singleChoice"] = True
                    create_field["choices"] = single_choice_field_dict[create_field["dataIndex"]]
                if field["dataIndex"] in json_fields:
                    field["show_type"] = json_fields_type[field["dataIndex"]]
                    field["content"] = json_fields_dict[field["dataIndex"]]
            data["create_fields"] = create_fields
            return make_get_success_response(data=data)
        except Exception as e:
            traceback.print_exc()
            return make_server_error_response(message=str(e), data=None)


class UnitSetModifyConfigView(View):
    def get(self, request):
        res = {"code": 400, "message": "", "data": None}
        try:
            data = {}
            modify_fields = get_model_serializer_config(
                UnitSetInfoModifySerializer)
            extra_fields = UnitSetInfoModifySerializer.get_extra_fields_info()
            for extra_field in extra_fields:
                for field in modify_fields:
                    if field["dataIndex"] == extra_field["dataIndex"]:
                        field["type"] = extra_field["type"]
                        field["title"] = extra_field["title"]
                        break
            single_choice_fields = ["origin_unit_set"]
            single_choice_field_dict = {}
            single_choice_field_dict["origin_unit_set"] = get_unit_set_choices(
            )
            json_fields = ["unitsetcontent"]
            json_fields_type = {"unitsetcontent": "tab"}
            json_fields_dict = {}
            unitsetcontent_content = []
            quantity_type_list = get_quantity_type_choices()
            availabel_quantitys = UnitSetContent.objects.all().values_list("quantity__uuid").distinct()
            for quantity_type in quantity_type_list:
                quantitys = Quantity.objects.filter(uuid__in = availabel_quantitys,
                    quantity_type=quantity_type["value"], valid_flag=True)
                if quantitys.count() == 0:
                    continue
                quantity_contents = []
                for quantity in quantitys:
                    quantity_contents.append({
                        "title": quantity.show_short_name(),
                        "dataIndex": quantity.uuid,
                        "type": "short_string",
                        "singleChoice": True,
                        "required": True,
                        "choices": get_valid_show_unit_choices_by_quantity(quantity)
                    })
                unitsetcontent_content.append({
                    "title": quantity_type["label"],
                    "dataIndex": quantity_type["value"],
                    "type": "json",
                    "content": quantity_contents
                })
            json_fields_dict["unitsetcontent"] = unitsetcontent_content
            for modify_field in modify_fields:
                modify_field["type"] = type_conversion_dict[modify_field["type"]]
                if modify_field["dataIndex"] in single_choice_fields:
                    modify_field["singleChoice"] = True
                    modify_field["choices"] = single_choice_field_dict[modify_field["dataIndex"]]
                if field["dataIndex"] in json_fields:
                    field["show_type"] = json_fields_type[field["dataIndex"]]
                    field["content"] = json_fields_dict[field["dataIndex"]]
            data["modify_fields"] = modify_fields
            return make_get_success_response(data=data)
        except Exception as e:
            traceback.print_exc()
            return make_server_error_response(message=str(e), data=None)

class UnitSetInfoConfigView(View):
    def get(self, request):
        res = {"code": 400, "message": "", "data": None}
        try:
            data = {}
            info_fields = get_model_serializer_config(
                UnitSetInfoSerializer)
            extra_fields = UnitSetInfoSerializer.get_extra_fields_info()
            for extra_field in extra_fields:
                for field in info_fields:
                    if field["dataIndex"] == extra_field["dataIndex"]:
                        field["type"] = extra_field["type"]
                        field["title"] = extra_field["title"]
                        break
            json_fields = ["unitsetcontent"]
            json_fields_type = {"unitsetcontent": "tab"}
            json_fields_dict = {}
            unitsetcontent_content = []
            quantity_type_list = get_quantity_type_choices()
            availabel_quantitys = UnitSetContent.objects.all().values_list("quantity__uuid").distinct()
            for quantity_type in quantity_type_list:
                quantitys = Quantity.objects.filter(uuid__in = availabel_quantitys,
                    quantity_type=quantity_type["value"], valid_flag=True)
                if quantitys.count() == 0:
                    continue
                quantity_contents = []
                for quantity in quantitys:
                    quantity_contents.append({
                        "title": quantity.show_short_name(),
                        "dataIndex": quantity.uuid,
                        "type": "short_string",
                        "singleChoice": True,
                        "required": True,
                        "choices": get_valid_show_unit_choices_by_quantity(quantity)
                    })
                unitsetcontent_content.append({
                    "title": quantity_type["label"],
                    "dataIndex": quantity_type["value"],
                    "type": "json",
                    "content": quantity_contents
                })
            json_fields_dict["unitsetcontent"] = unitsetcontent_content
            for info_field in info_fields:
                info_field["type"] = type_conversion_dict[info_field["type"]]
                if field["dataIndex"] in json_fields:
                    field["show_type"] = json_fields_type[field["dataIndex"]]
                    field["content"] = json_fields_dict[field["dataIndex"]]
            data["info_fields"] = info_fields
            return make_get_success_response(data=data)
        except Exception as e:
            traceback.print_exc()
            return make_server_error_response(message=str(e), data=None)